package com.tms.control;

import com.github.pagehelper.PageInfo;
import com.tms.domain.*;
import com.tms.quartz.service.QuartzService;
import com.tms.service.*;
import com.tms.utils.Data;
import com.tms.utils.DateUtil;
import com.tms.utils.JsonResult;
import com.tms.utils.description.DescriptionService;
import com.tms.utils.token.TokenService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;

import static com.tms.core.constants.ScrapConstants.*;
import static com.tms.core.constants.StatusConstants.*;

/**
 * 报废记录
 */
@RestController
@RequestMapping("api/scraps")
public class ScrapController extends BaseController {

    @Autowired
    private ScrapService scrapService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ToolService toolService;

    @Autowired
    private ToolStatusService toolStatusService;

    @Autowired
    private ScrapStatusService scrapStatusService;

    @Autowired
    private DescriptionService descriptionService;

    @Autowired
    private LifeCycleService lifeCycleService;

    @Autowired
    private LifeCycleStatusService lifeCycleStatusService;

    @Autowired
    private QuartzService quartzService;

    private DateUtil dateUtil = new DateUtil();

    private final String REMOVE = "remove";

    /**
     * 分页查看报废记录
     *
     * @param page     页数
     * @param pageSize 每页个数
     * @param request  获取token
     * @author cdx
     * @return 成功则返回scrap的list，失败则返回错误信息的JSON
     */
    @GetMapping
    public JsonResult viewScraps(@RequestParam(value = "page", defaultValue = "1") int page,
                                 @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                 @RequestParam(value = "status", defaultValue = "-1") int status,
                                 HttpServletRequest request) {
        //取出 user 用于获取 workcellId
        User requester = tokenService.getUserByRequest(request);
        if (requester == null || requester.getWorkcell() == null) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        PageInfo<Scrap> info = scrapService.findAllScraps(page, pageSize, status, requester.getWorkcell().getId());
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data("scraps", info));
    }

    /**
     * 查看某个id的报废记录
     *
     * @param id      scrap的id
     * @param request HttpServletRequest 获取token从而获取user
     * @return 成功则返回记录信息，失败则返回错误信息的JSON
     * @author cdx
     */
    @GetMapping("/{id}")
    public JsonResult viewScrap(@PathVariable(value = "id") int id, HttpServletRequest request) {
        // 取出workcellId 判断是否是同一部门
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        Scrap scrap = scrapService.findScrapById(id);
        // 判断是否有对应的 scrap
        if (scrap != null) {
            // 判断是否同一部门
            if (scrap.getSubPerson().getWorkcell().getId() == workcellId) {
                return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(scrap));
            }
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        } else {
            return new JsonResult(ERROR_NULL_SCRAP.getStatus(), ERROR_NULL_SCRAP.getDesc());
        }
    }

    /**
     * 提交报废记录
     *
     * @param map     参数map
     * @param request HttpServletRequest 获取token从而获取user
     * @return 成功返回提交的记录信息，失败返回错误信息
     */
    @PostMapping
    public JsonResult submitScrap(@RequestBody Map<String, String> map, HttpServletRequest request) {
        //获取前端传的值
        User submitPerson = tokenService.getUserByRequest(request);
        String description = map.get("description");
        int usedCount = Integer.parseInt(map.get("usedCount"));
        int toolId = Integer.parseInt(map.get("toolId"));
        Tool tool = toolService.findToolById(toolId);
        String stringTime = map.get("subTime");
        Date submitTime = dateUtil.getDate(stringTime);

        //构造 Scrap
        Status status = scrapStatusService.findById(SCRAP_JUST_SUBMIT.getStatus());
        Scrap scrap = new Scrap(description, usedCount, tool, submitPerson, null, null,
                submitTime, null, null, status);
        scrap.setWorkcell(submitPerson.getWorkcell());
        //写入 scrap
        scrapService.createScrap(scrap);

        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(scrap));
    }

    /**
     * 初审报废申请 jackie
     *
     * @param map 参数map
     * @param id  scrap记录id
     * @param req HttpServletRequest 获取token从而获取用户
     * @return 成功返回处理结果，失败返回错误信息
     * @author jackie
     * @date 2020年6月29日
     */
    @PatchMapping("/{id}/firstCheck")
    public JsonResult firstCheckScrap(@RequestBody Map<String, String> map, @PathVariable int id, HttpServletRequest req) {
        //判断Token
        User user = tokenService.getUserByRequest(req);
        //如果没有这个人
        if (user == null) {
            return new JsonResult(ERROR_NULL_USER.getStatus(), ERROR_NULL_USER.getDesc());
        }
        Scrap scrap = scrapService.findScrapById(id);
        if (scrap == null) {
            return new JsonResult(ERROR_NULL_SCRAP.getStatus(), ERROR_NULL_SCRAP.getDesc());
        } else if (scrap.getWorkcell().getId() != user.getWorkcell().getId()) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }
        int statusId = Integer.parseInt(map.get("status"));
        // 检查该status的结果是否已执行 或者 status已经是终止状态
        if (statusId <= scrap.getStatus().getId()
                || scrap.getStatus().getId() == SCRAP_FAILED_FIRST.getStatus()
                || scrap.getStatus().getId() == SCRAP_FAILED_SECOND.getStatus()
                || scrap.getStatus().getId() == SCRAP_SUCCESS_SECOND.getStatus()) {
            return new JsonResult(ERROR_REPEAT_STATUS.getStatus(), ERROR_REPEAT_STATUS.getDesc());
        }
        Date currentTime;
        try {
            currentTime = dateUtil.getCurrentDate();
        } catch (ParseException e) {
            e.printStackTrace();
            return new JsonResult();
        }
        Status scrapStatus = scrapStatusService.findById(statusId);
        scrap.setStatus(scrapStatus);
        Status lifeCycleStatus;
        LifeCycle lifeCycle;
        switch (statusId) {
            case 0:
                return new JsonResult(ERROR_NULL_STATUS.getStatus(), ERROR_NULL_STATUS.getDesc());
            case 1:
                scrap.setFirstPerson(user);
                scrap.setFirstTime(currentTime);

                //更新 lifeCycle
                lifeCycleStatus = lifeCycleStatusService.findById(LIFE_SCRAP.getStatus());
                lifeCycle = new LifeCycle(scrap.getTool(), lifeCycleStatus, scrap.getFirstPerson().getId(),
                        currentTime, descriptionService.getDescription(scrap));
                lifeCycleService.createLifeCycle(lifeCycle);
                break;
            case 2:
                scrap.setFirstPerson(user);
                scrap.setFirstTime(currentTime);
                break;
            case 3:
                scrap.setSecondPerson(user);
                scrap.setSecondTime(currentTime);

                //更新 lifeCycle
                lifeCycleStatus = lifeCycleStatusService.findById(LIFE_SCRAP.getStatus());
                lifeCycle = new LifeCycle(scrap.getTool(), lifeCycleStatus, scrap.getId(),
                        currentTime, descriptionService.getDescription(scrap));
                lifeCycleService.createLifeCycle(lifeCycle);
                break;
            case 4:
                scrap.setSecondPerson(user);
                scrap.setSecondTime(currentTime);

                // 更新 tool
                Status toolStatus = toolStatusService.findById(TOOL_SCRAPED.getStatus());
                Tool tool = scrap.getTool();
                tool.setStatus(toolStatus);
                toolService.updateToolById(tool);

                //更新 lifeCycle
                lifeCycleStatus = lifeCycleStatusService.findById(LIFE_SCRAP.getStatus());
                lifeCycle = new LifeCycle(scrap.getTool(), lifeCycleStatus, scrap.getId(),
                        currentTime, descriptionService.getDescription(scrap));
                lifeCycleService.createLifeCycle(lifeCycle);

                // 删除job
                if (!deleteJobAndTrigger(scrap.getTool())) {
                    return new JsonResult(ERROR_DELETE_JOB.getStatus(), ERROR_DELETE_JOB.getDesc());
                }
                break;
            default:
                return new JsonResult(ERROR_STATUS.getStatus(), ERROR_STATUS.getDesc());
        }
        scrapService.updateScrapById(scrap);
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(scrapService.findScrapById(id)));
    }

    /**
     * 终审报废入库申请 jackie
     *
     * @param map 参数map
     * @param id  scrap记录id
     * @param req HttpServletRequest 获取token从而获取用户
     * @return 成功返回处理结果，失败返回错误信息
     * @author jackie
     */
    @PatchMapping("/{id}/secondCheck")
    public JsonResult secondCheckScrap(@RequestBody Map<String, String> map, @PathVariable int id, HttpServletRequest req) {
        return firstCheckScrap(map, id, req);
    }

    /**
     * 删除模具的job和trigger
     *
     * @param tool 夹具对象
     * @return 成功返回true，失败返回false
     */
    private boolean deleteJobAndTrigger(Tool tool) {
        try {
            quartzService.handerJob(tool, 1, REMOVE);
            quartzService.handerJob(tool, 2, REMOVE);
            quartzService.handerTrigger(tool, 1, REMOVE);
            quartzService.handerTrigger(tool, 2, REMOVE);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}